<template>
	<div>

		<el-button  class="button-buy" type="primary" @click="centerDialogVisible = true" round>++++++++买入++++++++</el-button>

         <dev>
             <h1>历史交易记录 <p style="color:red"> 【盈利：{{profit}}】 </p></h1>
         </dev>
         
		<div class="pagination">
			<el-pagination 
			@size-change="handleSizeChange" 
			@current-change="handleCurrentChange" 
			:current-page="currentPage" 
			:page-sizes="[10, 20, 40,100]" 
			:page-size="pagesize" layout="total, sizes,prev, pager, next" 
			:total="tableData.length" prev-text="上一页" next-text="下一页">
			</el-pagination>
		</div>

        <el-table
		:row-class-name="tableRowClassName" 
		:header-cell-style="{background:'#000000',color:'#CD0000'}" 
		:data="tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)" 

		style="width: 100% ;font-size: 20px;">
			<el-table-column prop="id" label="序号" width="120">
			</el-table-column>
            <el-table-column prop="code" label="编号" width="120">
			</el-table-column>
			<el-table-column prop="name" label="名称" width="120">
			</el-table-column>
            <el-table-column
                prop="type"
                label="操作类型"
                width="120"
                filter-placement="bottom-end">
                <template slot-scope="scope">
                    <el-tag 
                        type='sucess'
                        v-if="scope.row.operation === 1"
                        effect="dark">
                    买
                    </el-tag>
                    <el-tag
                        type='info'
                        v-if="scope.row.operation === 0"
                        effect="dark">
                    卖
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="pric" :formatter="pricFormat" label="价格" >
			</el-table-column>
            <el-table-column prop="totalNum" label="数量" width="120">
			</el-table-column>
            <el-table-column prop="surplusNum" label="剩余" width="120">
			</el-table-column>
            <el-table-column prop="cost" label="手续费" width="120">
			</el-table-column>
            <el-table-column label="操作时间" width="200">
				<template slot-scope="scope">
					<i class="el-icon-time"></i>
					<span style="margin-left: 10px">{{ scope.row.operationTime }}</span>
				</template>
			</el-table-column>
			<el-table-column label="操作" width="200">
				<template slot-scope="scope">
					<!-- <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button> -->
                    <el-button v-if="scope.row.surplusNum>0" type="primary" round @click="handleSell(scope.$index, scope.row)">卖--出</el-button>
                    <!-- <el-button type="danger" icon="el-icon-delete" circle  @click="handleDelete(scope.$index, scope.row)"></el-button> -->
                  
				</template>
			</el-table-column>
		</el-table>

		<el-dialog title="新增交易" :visible.sync="centerDialogVisible" width="40%" center>
			<el-form :model="form" ref="form" label-width="80px">
				<el-form-item label="股票">
					<!-- <el-input v-model="form.name" autocomplete="off"></el-input> -->
                    <el-select v-model="form.name" placeholder="请选择" size="small">
                        <el-option v-for="item in optionList"  :key="item.code" :label="item.name" :value="`${item.name}|${item.code}`">
                        </el-option>
                    </el-select>
				</el-form-item>

                <!-- <el-form-item label="股票编号">
					<el-input v-model="form.code" autocomplete="off"></el-input>
				</el-form-item> -->
                <el-form-item label="类型">
                    <el-radio-group v-model="form.operation">
                    <el-radio label="1" >买</el-radio>
                    <!-- <el-radio label="0">卖</el-radio> -->
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="价格">
					<!-- <el-input v-model.number="form.pric" autocomplete="off"></el-input> -->
                    <el-input-number v-model="form.pric" :precision="2" :step="0.1" :max="1000"></el-input-number>
				</el-form-item>
                <el-form-item label="数量">
                    <el-input-number v-model="form.totalNum"  :min="100" :max="100000" :step="100" ></el-input-number>
				</el-form-item>
                <el-form-item label="时间">
                     <el-date-picker type="date" placeholder="选择日期" v-model="form.operationTime" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" style="width: 100%;"></el-date-picker>
                </el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="centerDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="handleSave">确 定</el-button>
			</span>
		</el-dialog>



		<el-dialog title="修改" :visible.sync="dialogEditgsVisible" width="40%" center>
			<el-form :model="editForm" ref="editForm">
				<el-form-item label="序号">
					<el-input v-model="editForm.id" disabled autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="名称">
					<el-input v-model="editForm.name" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="操作类型">
					<el-input v-model.number="editForm.operation"></el-input>
				</el-form-item>
			</el-form>

			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogEditgsVisible = false">取 消</el-button>
				<el-button type="primary" @click="saveEditForm('editForm')">更 新</el-button>
			</div>
		</el-dialog>

        <el-dialog title="卖出" :visible.sync="dialogSellgsVisible" width="40%" center>
			<el-form :model="sellForm" ref="editForm">
				<el-form-item label="序号">
					<el-input v-model="sellForm.id" disabled autocomplete="off"></el-input>
				</el-form-item>
                <el-form-item label="时间">
                     <el-date-picker type="date" placeholder="选择日期" v-model="sellForm.operationTime" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" style="width: 100%;"></el-date-picker>
                </el-form-item>
                参考:
                <el-tag>买入价{{sellForm.pricOld}}</el-tag>
                <el-tag>剩余数量{{sellForm.surplusNumOld}}</el-tag>
               
				<el-form-item label="卖出价格">
                     <el-input-number v-model="sellForm.pric" :precision="2" :step="0.1" ></el-input-number>
				</el-form-item>
				<el-form-item label="数量">
                    <el-input-number v-model="sellForm.surplusNum" :max="sellForm.surplusNumOld" :step="100" ></el-input-number>
				</el-form-item>

			</el-form>

			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogSellgsVisible = false">取 消</el-button>
				<el-button type="primary" @click="saveEditForm('sellForm')">更 新</el-button>
			</div>
		</el-dialog>
	</div>

</template>
<style>
  .el-table .buy-row {
    background: #FFF5EE;
    color: #104E8B;
  }

  .el-table .sell-row {
    background: #F4F4F4;
    color: #104E8B;
  }
  .button-buy{
    width: 20%;
    height: 150px;
  }
  
</style>
<script>
	import axios from "axios";
	import Qs from 'qs'

	export default {
		name: "Home",
		data() {
			return {
				name: '',
				currentPage: 1, //默认显示页面为1
				pagesize: 10, //    每页的数据条数
				tableData: [], //需要data定义一些，tableData定义一个空数组，请求的数据都是存放这里面
				centerDialogVisible: false,
                dialogEditgsVisible: false,
				dialogSellgsVisible:false,
				profit:'',
                optionList:[
                    {name:"招商银行",code:"600036"},
                    {name:"海康威视",code:"002415"},
                    {name:"格力电器",code:"000651"}
                ],
				form: {
                    name: '',
                    code:'',
                    operation: "1",
                    pric: '',
                    totalNum:'',
                    operationTime:'',
                },
				editForm: {
                    id: '',                   
					name: '',
					operation: '',
                },
                sellForm: {  
                    id: '', 
                    surplusNum: '',
                    pric: '',
                    pricOld: '',
                    surplusNumOld:'',
                    operationTime:'',
				}
			}
        },
        
		mounted() {
			this.getData();
			this.statisticsProfit();
		},
		methods: {
			pricFormat(row){
				if(row.surplusNum>0){
					return "[" +row.pric.toFixed(2)+"]-------["+(row.pric+0.3).toFixed(2) +"]--["+(row.pric*1.02+0.1).toFixed(2)+"]"
				}else{
					return row.pric.toFixed(2)
				}
			},
            tableRowClassName({row}) {
                if (row.operation === 1) {
                return 'buy-row';
                } else {
                return 'sell-row';
                }
                // eslint-disable-next-line no-unreachable
                return '';
			},
			getData() {
				axios.get('http://localhost/stock-tr/list').then(response => {
					console.log(response.data);
					this.tableData = response.data.data;
				}, response => {
					console.log("error"+response);
				});
			},
			statisticsProfit() {
				axios.get('http://localhost/stock-tr/statistics-profit').then(response => {
					console.log(response.data);
					this.profit = response.data.data;
				}, response => {
					console.log("error"+response);
				});
			},
			handleSave() {
                this.centerDialogVisible = false;
                
                let [lable,vaue] = this.form.name.split('|') // es6 数组解构赋值

				this.$refs.form.validate((valid) => {
					if (valid) {
						this.logining = true;
						this.$axios({
								method: "post",
								url: "http://localhost/stock-tr/save", // 接口地址
								data: {
                                    name: lable, // 传接口参数
                                    code: vaue, // 传接口参数
                                    operation: Number(this.form.operation),
                                    pric: this.form.pric,
                                    totalNum: this.form.totalNum,     
                                    operationTime: this.form.operationTime     
								}
							})
							.then(response => {
								if (response.data.code == 200) {
									this.$message({
										showClose: true,
										message: response.data.msg,
										type: 'success'
									});
								} else {
									this.$message({
										showClose: true,
										message: response.data.msg,
										type: 'warning'
									});
								} // 成功的返回      
							})
							.catch(error => console.log(error, "error")); // 失败的返回
						this.logining = false;
					} else {
						console.log('error submit!');
						return false;
                    }
                    this.getData();
                })
                this.$router.go(0);
			},

			//每页下拉显示数据
			handleSizeChange: function(size) {
				this.pagesize = size;
				/*console.log(this.pagesize) */
			},
			//点击第几页
			handleCurrentChange: function(currentPage) {
				this.currentPage = currentPage;
				/*console.log(this.currentPage) */
			},
			// 点击编辑按钮，弹出编辑模态框
			handleEdit(index, row) {
				this.dialogEditgsVisible = true;
				this.editForm.id = row.id;
				this.editForm.name = row.name;
				this.editForm.operation = row.operation;
            },         			
            // 点击编辑按钮，弹出编辑模态框
			handleSell(index, row) {
				this.dialogSellgsVisible = true;
				this.sellForm.id = row.id;
                this.sellForm.pric = row.pric;
                this.sellForm.pricOld = row.pric;
                this.sellForm.surplusNum = row.surplusNum;
                this.sellForm.surplusNumOld = row.surplusNum;
                this.sellForm.operationTime = row.operationTime;
                
            },
			//更新编辑数据
			saveEditForm(type) {
                if(type=="sellForm"){
                    console.log("type2"+type);
                    this.$refs.editForm.validate((valid) => {
                        if (valid) {
                            this.logining = true;
                            this.$axios({
                                    method: "post",
                                    url: "http://localhost/stock-tr/sell", // 接口地址
                                    data: {
                                        surplusNum: this.sellForm.surplusNum , 
                                        operationTime:this.sellForm.operationTime,
                                        pric: this.sellForm.pric,
                                        id: this.sellForm.id
                                    }
                                })
                                .then(response => {
                                    this.dialogSellgsVisible = false;
                                    if (response.data.code == 200) {
                                        this.$message({
                                            showClose: true,
                                            message: response.data.msg,
                                            type: 'success'
                                        });
                                    } else {
                                        this.$message({
                                            showClose: true,
                                            message: response.data.msg,
                                            type: 'warning'
                                        });
                                    } // 成功的返回      
                                })
                                .catch(error => console.log(error, "error")); // 失败的返回
                            this.logining = false;
                        } else {
                            console.log('error submit!');
                            return false;
                        }
                
                    })


                }else{
                this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.logining = true;
						this.$axios({
								method: "post",
								url: "http://localhost/stock-tr/edit", // 接口地址
								data: {
									name: this.editForm.name, // 传接口参数
									operation: Number(this.editForm.age),
									id: this.editForm.id
								}
							})
							.then(response => {
								this.dialogEditgsVisible = false;
								if (response.data.code == 200) {
									this.$message({
										showClose: true,
										message: response.data.msg,
										type: 'success'
									});
								} else {
									this.$message({
										showClose: true,
										message: response.data.msg,
										type: 'warning'
									});


								} // 成功的返回      
							})
							.catch(error => console.log(error, "error")); // 失败的返回
						this.logining = false;
					} else {
						console.log('error submit!');
						return false;
					}
                })
                }
                this.$router.go(0);
			},
			// 删除
			handleDelete(index, row) {
				axios({
						method: "POST",
						url: "http://localhost/stock-tr/del", // 接口地址
						transformRequest: [function(data) {
							// 对 data 进行任意转换处理
							return Qs.stringify(data)
						}],
						headers: {
							'deviceCode': 'A95ZEF1-47B5-AC90BF3'
						},
						data: {
							id: row.id
						},
					})
					.then(response => {
						if (response.data.code == 200) {
							this.$message({
								showClose: true,
								message: response.data.msg,
								type: 'success'
							});
						} else {
							this.$message({
								showClose: true,
								message: response.data.msg,
								type: 'warning'
							});
						}
						console.log(response, "success"); // 成功的返回      
                    })
                    this.$router.go(0)
            }
            

		}
	}
</script>
<style>
</style>
